<template>
  <div class="mobile-seat">
    <!-- 顶部导航栏 -->
    <div class="mobile-nav-bar">
      <el-icon @click="goBack">
        <ArrowLeft />
      </el-icon>
      <span class="nav-title">选择座位</span>
      <div class="placeholder"></div>
    </div>

    <!-- 电影和场次信息 -->
    <div class="movie-info" v-if="movieDetail && showDetail">
      <div class="movie-basic">
        <img :src="movieDetail.photo" alt="电影海报" class="movie-poster" />
        <div class="movie-meta">
          <h3 class="movie-title">{{ movieDetail.name }}</h3>
          <div class="movie-time">{{ formatTime(showDetail.time) }}</div>
          <div class="movie-hall">{{ showDetail.name }}</div>
          <div class="movie-price">¥{{ movieDetail.price }}/张</div>
        </div>
      </div>
    </div>

    <!-- 座位选择区域 -->
    <div class="seat-section">
      <div class="seat-legend">
        <div class="legend-item">
          <span class="seat-available"></span>
          <span>可选</span>
        </div>
        <div class="legend-item">
          <span class="seat-selected"></span>
          <span>已选</span>
        </div>
        <div class="legend-item">
          <span class="seat-occupied"></span>
          <span>已售</span>
        </div>
      </div>

      <div class="seat-map-container">
        <div class="screen-container">
          <div class="screen">银幕</div>
        </div>

        <div class="seats-container">
          <div class="seat-row" v-for="row in 6" :key="'row-'+row">
            <div class="row-label">{{ String.fromCharCode(64 + row) }}</div>
            <div
              v-for="col in 6"
              :key="'seat-'+(row-1)*6+col"
              class="seat"
              :class="getSeatClass((row-1)*6+col)"
              @click="toggleSeat((row-1)*6+col)"
            >
              <el-tooltip :content="String.fromCharCode(64 + row) + col" placement="top"
                          :show-after="500">
                <div class="seat-inner">{{ col }}</div>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 已选座位和订单信息 -->
    <div class="order-section">
      <div class="selected-seat-info">
        <div class="info-label">已选座位：</div>
        <div class="info-value">{{ getSelectedSeatsText }}</div>
      </div>
      <div class="ticket-count-section">
        <div class="info-label">票数：</div>
        <div class="ticket-counter">
          <el-button
            size="small"
            circle
            @click="decreaseTicketCount"
            :disabled="ticketCount <= 1"
            class="counter-btn"
          >
            <el-icon>
              <Remove />
            </el-icon>
          </el-button>
          <span class="ticket-count">{{ ticketCount }}</span>
          <el-button
            size="small"
            circle
            @click="increaseTicketCount"
            :disabled="ticketCount >= 4"
            class="counter-btn"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
        </div>
      </div>
      <div class="order-price">
        <div class="info-label">订单金额：</div>
        <div class="info-value price">¥{{ totalPrice }}</div>
      </div>
    </div>

    <!-- 提交订单按钮 -->
    <div class="submit-order">
      <el-button
        type="danger"
        :disabled="selectedSeats.length === 0 || !showDetail || selectedSeats.length !== ticketCount"
        @click="submitOrder"
        class="submit-btn"
      >
        提交订单
      </el-button>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft, Plus, Remove } from "@element-plus/icons-vue";
import {
  mobileReqFilmDetail,
  mobileReqFilmShow,
  mobileReturnSeatByMovieId,
  mobileReqFilmOrder
} from "@/api/mobile/index.ts";
import { formatTime as formatTimeUtil } from "@/util/common.ts";

const route = useRoute();
const router = useRouter();
const movieDetail = ref(null);
const showDetail = ref(null);
const occupiedSeats = ref([]);
const selectedSeats = ref([]);
const loading = ref(true);
const showId = ref(Number(route.params.showId));
const MovieId = ref(Number(route.params.movieId));
const ticketCount = ref(1);
let userId = ref(localStorage.getItem("id"));
// 计算总价
const totalPrice = computed(() => {
  if (!movieDetail.value || selectedSeats.value.length === 0) return 0;
  return movieDetail.value.price * selectedSeats.value.length;
});

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取电影详情
const getMovieDetail = async () => {
  try {
    // 再获取电影详情
    const result = await mobileReqFilmDetail(MovieId.value);
    if (result.code === 200) {
      movieDetail.value = result.data;
    } else {
      ElMessage.error(result.message || "获取电影详情失败");
    }
  } catch (error) {
    console.error("获取电影详情出错", error);
    ElMessage.error("获取电影详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取场次详情
const getShowDetail = async () => {
  try {
    // 获取所有场次
    const result = await mobileReqFilmShow(MovieId.value);
    if (result.code === 200) {
      // 从所有场次中找到当前场次
      const currentShow = result.data.find(item => item.id === showId.value);
      if (currentShow) {
        showDetail.value = currentShow;
        return true;
      } else {
        ElMessage.error("未找到该场次信息");
        return false;
      }
    } else {
      ElMessage.error(result.message || "获取场次信息失败");
      return false;
    }
  } catch (error) {
    console.error("获取场次信息出错", error);
    ElMessage.error("获取场次信息失败");
    return false;
  }
};

// 获取已售座位
const getOccupiedSeats = async () => {
  try {

    const result = await mobileReturnSeatByMovieId(MovieId.value);
    if (result.code === 1) {
      occupiedSeats.value = result.data.map(item => parseInt(item.message));
    } else {
      ElMessage.error(result.message || "获取座位信息失败");
    }
  } catch (error) {
    console.error("获取座位信息出错", error);
    ElMessage.error("获取座位信息失败");
  }
};

// 获取座位的CSS类
const getSeatClass = (index) => {
  if (occupiedSeats.value.includes(index)) {
    return "seat-occupied";
  }
  return selectedSeats.value.includes(index) ? "seat-selected" : "";
};

// 选择座位
const toggleSeat = (index) => {
  if (occupiedSeats.value.includes(index)) {
    ElMessage.error("该座位已被购买");
    return;
  }

  const seatIndex = selectedSeats.value.indexOf(index);

  // 如果已经选择了这个座位，则取消选择
  if (seatIndex !== -1) {
    selectedSeats.value.splice(seatIndex, 1);
    return;
  }

  // 如果选择的座位数量已经达到票数，则提示用户
  if (selectedSeats.value.length >= ticketCount.value) {
    ElMessage.warning(`最多只能选择${ticketCount.value}个座位`);
    return;
  }

  // 添加新选择的座位
  selectedSeats.value.push(index);
};

// 增加票数
const increaseTicketCount = () => {
  if (ticketCount.value < 4) { // 限制最多4张票
    ticketCount.value++;
  } else {
    ElMessage.warning("每次最多购买4张票");
  }
};

// 减少票数
const decreaseTicketCount = () => {
  if (ticketCount.value > 1) {
    // 如果减少票数后，已选座位数量超过新票数，则移除多余的座位
    if (selectedSeats.value.length > ticketCount.value - 1) {
      selectedSeats.value = selectedSeats.value.slice(0, ticketCount.value - 1);
    }
    ticketCount.value--;
  }
};

// 获取座位信息
const getSeats = () => {
  // 获取所有已选座位的信息
  return selectedSeats.value.map(seat => {
    const row = Math.floor(seat / 6) + 1;
    const col = seat % 6;
    // 处理第0列的情况
    const actualCol = col === 0 ? 6 : col;
    // 返回格式化的座位信息，例如：A1, B2等
    return String.fromCharCode(64 + row) + actualCol;
  });
};

// 获取已选座位的文本描述
const getSelectedSeatsText = computed(() => {
  if (selectedSeats.value.length === 0) return "请选择座位";
  // 使用新的getSeats函数获取格式化的座位信息
  return getSeats().join("、");
});

// 提交订单
const submitOrder = async () => {
  if (selectedSeats.value.length === 0) {
    ElMessage.warning("请选择座位");
    return;
  }

  if (selectedSeats.value.length !== ticketCount.value) {
    ElMessage.warning(`请选择${ticketCount.value}个座位`);
    return;
  }

  if (!showDetail.value) {
    ElMessage.warning("场次信息不完整");
    return;
  }

  try {
    // 使用新的getSeats函数获取座位信息
    const seatsArray = getSeats();
    const seatsText = seatsArray.join("、");

    ElMessageBox.confirm(
      `确认购买 ${movieDetail.value.name} ${formatTime(showDetail.value.time)} ${showDetail.value.name} ${seatsText}？`,
      "确认订单",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      // 创建订单数据
      const orderPromises = selectedSeats.value.map((seat, index) => {
        const orderData = {
          movieId: MovieId.value,
          showNameId: showId.value,
          message: selectedSeats.value[index], // 使用格式化后的座位信息
          sum: ticketCount.value,
          amount: totalPrice.value,
          userId: userId.value
        };
        return mobileReqFilmOrder(orderData);
      });

      // 并行处理所有订单
      const results = await Promise.all(orderPromises);

      // 检查是否所有订单都成功
      const allSuccess = results.every(result => result.code === 1);

      if (allSuccess) {
        ElMessage.success("购票成功");
        // 跳转到订单页面
        router.push("/mobile/order");
      } else {
        ElMessage.error("部分或全部座位购票失败，请重试");
      }
    }).catch(() => {
      // 用户取消操作
    });
  } catch (error) {
    console.error("提交订单出错", error);
    ElMessage.error("提交订单失败");
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr || !Array.isArray(timeStr)) return "";
  return formatTimeUtil(timeStr);
};

onMounted(async () => {
  await getShowDetail();
  await getMovieDetail();
  await getOccupiedSeats();
});
</script>

<style scoped lang="scss">
.mobile-seat {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 80px; // 为底部按钮留出空间
}

.mobile-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .el-icon {
    font-size: 20px;
    cursor: pointer;
  }

  .nav-title {
    font-size: 18px;
    font-weight: bold;
  }

  .placeholder {
    width: 20px;
  }
}

.movie-info {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .movie-basic {
    display: flex;
    gap: 12px;

    .movie-poster {
      width: 80px;
      height: 120px;
      border-radius: 6px;
      object-fit: cover;
    }

    .movie-meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .movie-title {
        font-size: 18px;
        margin: 0 0 8px;
      }

      .movie-time,
      .movie-hall,
      .movie-price {
        font-size: 14px;
        color: #606266;
        margin-bottom: 5px;
      }

      .movie-price {
        color: #ff6b6b;
        font-weight: bold;
      }
    }
  }
}

.seat-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.seat-legend {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 15px;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
  }

  .seat-available,
  .seat-selected,
  .seat-occupied {
    display: inline-block;
    width: 16px;
    height: 16px;
    border-radius: 3px;
  }

  .seat-available {
    background-color: #e0e0e0;
    border: 1px solid #ccc;
  }

  .seat-selected {
    background-color: #409eff;
    border: 1px solid #409eff;
  }

  .seat-occupied {
    background-color: #f56c6c;
    border: 1px solid #f56c6c;
  }
}

.seat-map-container {
  margin: 0 auto;
  max-width: 100%;
  overflow-x: auto;
  padding-bottom: 15px;
}

.screen-container {
  display: flex;
  justify-content: center;
  margin-bottom: 25px;

  .screen {
    width: 85%;
    height: 35px;
    background: linear-gradient(to bottom, #e0e0e0, #f5f5f5);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #606266;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: relative;

    &:after {
      content: '';
      position: absolute;
      bottom: -10px;
      left: 0;
      right: 0;
      height: 10px;
      background: linear-gradient(to bottom, rgba(0, 0, 0, 0.05), transparent);
    }
  }
}

.seats-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 5px;
  margin: 0 auto;
  max-width: 100%;
}

.seat-row {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;

  .row-label {
    width: 20px;
    text-align: center;
    font-size: 14px;
    color: #606266;
    font-weight: bold;
  }
}

.seat {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;

  .seat-inner {
    width: 24px;
    height: 24px;
    border-radius: 4px;
    background-color: #e0e0e0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #606266;
    transition: all 0.2s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  &:active .seat-inner {
    transform: scale(0.95);
  }

  &:hover .seat-inner {
    background-color: #d0d0d0;
  }

  &.seat-selected .seat-inner {
    background-color: #409eff;
    color: #fff;
    box-shadow: 0 2px 5px rgba(64, 158, 255, 0.3);
  }

  &.seat-occupied .seat-inner {
    background-color: #f56c6c;
    color: #fff;
    cursor: not-allowed;
    box-shadow: 0 2px 5px rgba(245, 108, 108, 0.3);
  }
}

.order-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  .selected-seat-info,
  .ticket-count-section,
  .order-price {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    align-items: center;
  }

  .info-label {
    font-size: 14px;
    color: #606266;
    min-width: 70px;
  }

  .info-value {
    font-size: 14px;
    font-weight: bold;
    flex: 1;
    text-align: right;

    &.price {
      color: #ff6b6b;
      font-size: 16px;
    }
  }

  .ticket-counter {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    flex: 1;

    .counter-btn {
      padding: 4px;
      margin: 0 8px;
    }

    .ticket-count {
      font-size: 16px;
      font-weight: bold;
      min-width: 24px;
      text-align: center;
    }
  }
}

.submit-order {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;

  .submit-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
  }
}

.loading-container {
  padding: 20px 15px;
}
</style>
